#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        vector<vector<int>> ans(matrix.size(), vector<int>(matrix[0].size(), INT32_MAX / 2));
        int height = matrix.size();
        int width = matrix[0].size();
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (matrix[i][j] == 0) {
                    ans[i][j] = 0;
                }
            }
        }
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (matrix[i][j] == 0) {
                    continue;
                }
                if (i > 0) {
                    ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1);
                }
                if (j > 0) {
                    ans[i][j] = min(ans[i][j], ans[i][j - 1] + 1);
                }
            }
        }
        for (int i = height - 1; i >= 0; i--) {
            for (int j = width - 1; j >= 0; j--) {
                if (matrix[i][j] == 0) {
                    continue;
                }
                if (i < height - 1) {
                    ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1);
                }
                if (j < width - 1) {
                    ans[i][j] = min(ans[i][j], ans[i][j + 1] + 1);
                }
            }
        }
        return ans;
    }
};
